package com.li.blog.controller;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.DES;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.li.blog.common.dto.Email;
import com.li.blog.common.dto.LoginDto;
import com.li.blog.common.dto.RegiserDto;
import com.li.blog.common.lang.Result;
import com.li.blog.entity.User;
import com.li.blog.service.UserService;
import com.li.blog.utils.JwtUtils;
import com.li.blog.utils.MailUtils;
import com.li.blog.utils.OnlineCounter;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.ResultSet;
import java.time.LocalDateTime;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author HP
 */
@RestController
public class AccountController {

    @Autowired
    UserService userService;

    @Autowired
    private OnlineCounter onlineCounter;

    //开启邮箱服务
    @Autowired
    private MailUtils sendMail;
    //开启redis
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    JwtUtils jwtUtils;
    @PostMapping("/login")
    public Result login(@Validated @RequestBody LoginDto loginDto, HttpServletResponse response){
        User user = userService.getOne(new QueryWrapper<User>().eq("username", loginDto.getUsername()));
        Assert.notNull(user,"用户不存在");

        if(!user.getPassword().equals(SecureUtil.md5(loginDto.getPassword()))){
            return Result.fail("密码不正确");
        }
        String jwt = jwtUtils.generateToken(user.getId());

        response.setHeader("Authorization",jwt);
        response.setHeader("Access-control-Expose-Headers","Authorization");

        return Result.succ(MapUtil.builder()
                .put("id",user.getId())
                .put("username",user.getUsername())
                .put("avatar",user.getAvatar())
                .put("email",user.getEmail())
                        .put("password",user.getPassword())
                .map());
    }
    @RequiresAuthentication
    @GetMapping("/logout")
    public Result logout(){
        SecurityUtils.getSubject().logout();
        return Result.succ(null);
    }

    /**
     * @auther: Arong
     * @description: 获取当前实时在线人数(精确度为60s范围内)
     * @param
     * @return: int
     * @date: 2019/1/19 17:44
     */
    @GetMapping(value = "/getOnlineCount")
    public Result getRealOnlineCount() {
        Integer onlines = onlineCounter.getOnlineCount();
        return Result.succ(onlines);
    }

    @RequestMapping(value = "/mail",method = RequestMethod.POST)
    public Result mail(@RequestBody @Validated Email email)
    {
        //模拟真实业务
        String code= redisTemplate.opsForValue().get(email.getEmail());
        if(!StringUtils.isEmpty(code))
        {
            String s = redisTemplate.opsForValue().get(email.getEmail());
            return Result.succ("验证码已经发送了，请耐心等待");
        }
        //生产随机的四位验证码！！
        code = UUID.randomUUID().toString().substring(0,4);
        sendMail.MailMessage(code,email.getEmail());
        redisTemplate.opsForValue().set(email.getEmail(),code,5, TimeUnit.MINUTES);
        return Result.succ("邮件发送成功！");
    }
    @PostMapping("/register")
    public Result Register(@RequestBody @Validated RegiserDto regiserDto)
    {
        //判断用户名是否已经存在
        String vertify = redisTemplate.opsForValue().get(regiserDto.getEmail());
        if(vertify==null ||!vertify.equals(regiserDto.getVertifyCode())){
            return Result.fail("验证码不正确！");
        }
        User user = userService.getOne(new QueryWrapper<User>().eq("username", regiserDto.getUsername()));
        if(user!=null){
            return Result.fail("用户明已存在,请重新填写！");
        }
        User Nowuser = new User();
        Nowuser.setUsername(regiserDto.getUsername());
        Nowuser.setPassword(SecureUtil.md5(regiserDto.getPassword()));
        Nowuser.setEmail(regiserDto.getEmail());
        Nowuser.setStatus(0);
        Nowuser.setCreated(LocalDateTime.now());
        Nowuser.setAvatar("https://tse1-mm.cn.bing.net/th/id/OIP-C.3qHJ-AhAr11VkzMbNMYFHwAAAA?w=138&h=148&c=7&r=0&o=5&dpr=1.25&pid=1.7");
        userService.save(Nowuser);
        return Result.succ("注册成功");
    }
}
